package com.lemner.ke.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.laojiang.imagepickers.ImagePicker;
import com.laojiang.imagepickers.data.ImagePickType;
import com.laojiang.imagepickers.data.MediaDataBean;
import com.lemner.ke.R;
import com.lemner.ke.base.BaseActivity;
import com.lemner.ke.base.BaseListener;
import com.lemner.ke.base.BaseObjectBean;
import com.lemner.ke.base.SuccessListener;
import com.lemner.ke.base.URL;
import com.lemner.ke.bean.SuccessBean;
import com.lemner.ke.bean.UserBean;
import com.lemner.ke.model.persional.GetUserByIdsModel;
import com.lemner.ke.model.persional.ResetBirthdayModel;
import com.lemner.ke.model.persional.ResetGenderModel;
import com.lemner.ke.model.persional.ResetHeadModel;
import com.lemner.ke.util.LoadImageUtils;
import com.lemner.ke.util.MyImagePicker;
import com.lemner.ke.util.PhotoAlbumUtil;
import com.lemner.ke.util.SpUtils;
import com.lemner.ke.view.CustomDatePicker;
import com.lemner.ke.view.MyPopWindow;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**

* 作者：张恺

* 时间：2018/9/25

* 类描述：个人资料页面

*/

public class PersonalActivity extends BaseActivity {
    private Bitmap bitmap;
    private RelativeLayout rl_head;
    private MyPopWindow popup_img;
    private CircleImageView civ_head;
    private RelativeLayout rl_name, rl_sex, rl_age;
    private TextView tv_name, tv_sex, tv_age;
    String name;
    private CustomDatePicker customDatePicker;

    @Override
    public int getLayoutFile() {
        return R.layout.activity_personal;
    }

    @Override
    public void initView() {
        topBar.setTitle("个人资料");
        rl_head = findViewById(R.id.rl_personal_head);
        civ_head = findViewById(R.id.civ_personal_head);
        rl_name = findViewById(R.id.rl_personal_name);
        rl_sex = findViewById(R.id.rl_personal_sex);
        rl_age = findViewById(R.id.rl_personal_age);
        tv_name = findViewById(R.id.tv_personal_name);
        tv_sex = findViewById(R.id.tv_personal_sex);
        tv_age = findViewById(R.id.tv_personal_age);
    }

    @Override
    public void initEvent() {
        rl_head.setOnClickListener(this);
        civ_head.setOnClickListener(this);
        rl_name.setOnClickListener(this);
        rl_sex.setOnClickListener(this);
        rl_age.setOnClickListener(this);
    }

    @Override
    public void initData() {
        updateData();
        initPopImg();
        initDatePicker();
    }

    @Override
    protected void initSetting() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_personal_head:
                popup_img.showAtLocation();
                break;
            case R.id.rl_personal_name:
                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                startActivity(NameActivity.class, bundle);
                break;
            case R.id.rl_personal_sex:
                final MyPopWindow myPopWindow = new MyPopWindow(this);
                myPopWindow.addButton("男", new View.OnClickListener() {
                        @Override
                    public void onClick(View v) {
                        myPopWindow.dismiss();
                        new ResetGenderModel().resetGender(SpUtils.getString(PersonalActivity.this, SpUtils.USERIDS), SpUtils.getString(PersonalActivity.this, SpUtils.MOBILE_PHOE), 1, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                tv_sex.setText("男");
                                showToast("修改性别成功");
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });
                    }
                });
                myPopWindow.addButton("女", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myPopWindow.dismiss();
                        new ResetGenderModel().resetGender(SpUtils.getString(PersonalActivity.this, SpUtils.USERIDS), SpUtils.getString(PersonalActivity.this, SpUtils.MOBILE_PHOE), 0, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                tv_sex.setText("女");
                                showToast("修改性别成功");
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });
                    }
                });
                myPopWindow.showAtLocation();
                break;
            case R.id.rl_personal_age:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date()).split(" ")[0];
                customDatePicker.show(now);
                break;
        }
    }

    private void initPopImg() {
        popup_img = new MyPopWindow(this);
        popup_img.addButton("相册", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popup_img.dismiss();
                new MyImagePicker(PersonalActivity.this, ImagePickType.SINGLE, false);
            }
        });
        popup_img.addButton("相机", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popup_img.dismiss();
                PermissionGen.with(PersonalActivity.this).addRequestCode(105)
                        .permissions(Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 105)
    public void doSomething() {
        new MyImagePicker(PersonalActivity.this, ImagePickType.ONLY_CAMERA, true);
    }

    @PermissionFail(requestCode = 105)
    public void doFailSomething() {
        showToast("相机权限打开失败！");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == MyImagePicker.RESULT_CODE && data != null) {
            super.onActivityResult(requestCode, resultCode, data);
            List<MediaDataBean> resultList = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
            File picture = new File(resultList.get(0).getMediaPath());
            if (picture.exists()) {
                bitmap = PhotoAlbumUtil.getBitmapFromUri(this, Uri.fromFile(picture));
                bitmap = PhotoAlbumUtil.zoomImage(this, bitmap);
                RequestBody uid = RequestBody.create(MediaType.parse("multipart/form-data"), SpUtils.getString(PersonalActivity.this, SpUtils.USERIDS));
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), picture);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("user_covers", picture.getName(), requestFile);
                new ResetHeadModel().resetHead(uid, filePart, new BaseListener<SuccessBean>() {
                    @Override
                    public void onResponse(SuccessBean successBean) {
                        civ_head.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onFail(String msg) {

                    }
                });
            }
        }
    }

    public void updateData() {
        new GetUserByIdsModel().getUserByIds(SpUtils.getString(PersonalActivity.this, SpUtils.USERIDS), new BaseListener() {
            @Override
            public void onResponse(Object o) {
                UserBean userBean = ((BaseObjectBean<UserBean>) o).getData();
                String url = URL.BASE_URL + userBean.getHeadcovers();
                name = userBean.getNames();
                LoadImageUtils.loadImage(url, civ_head);
                tv_age.setText(userBean.getAge() + "");
                tv_name.setText(name);
                tv_sex.setText(userBean.getGender() == 2 ? "未知" : userBean.getGender() == 1 ? "男" : "女");
            }

            @Override
            public void onFail(String msg) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateData();
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        final String now = sdf.format(new Date());
        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                int age;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String nows = sdf.format(new Date());
                int yearAgo = Integer.parseInt(time.substring(0, 4));
                int monthAgo = Integer.parseInt(time.substring(5, 7));
                int dayAgo = Integer.parseInt(time.substring(8, 10));

                new ResetBirthdayModel().resetBirthday(SpUtils.getString(PersonalActivity.this, SpUtils.USERIDS), SpUtils.getString(PersonalActivity.this, SpUtils.MOBILE_PHOE), yearAgo + "-" + monthAgo + "-" + dayAgo
                        , new SuccessListener());

                int year = Integer.parseInt(nows.substring(0, 4));
                int month = Integer.parseInt(nows.substring(5, 7));
                int day = Integer.parseInt(nows.substring(8, 10));

                if (monthAgo > month) {
                    age = year - yearAgo - 1;
                } else if ((monthAgo == month) && (dayAgo > day)) {
                    age = year - yearAgo - 1;
                } else {
                    age = year - yearAgo;
                }
                String ageS = String.valueOf(age) + "岁";
                tv_age.setText(ageS);
                showToast("修改年龄成功");
            }
        }, "1950-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(true); // 不允许循环滚动
    }
}
